package com.sbtr.business.calibration.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbtr.business.calibration.entity.Calibration;
import com.sbtr.business.calibration.entity.CalibrationDetails;
import com.sbtr.business.calibration.entity.CalibrationRecordDaily;
import com.sbtr.business.calibration.entity.CalibrationVoice;
import com.sbtr.business.calibration.mapper.CalibrationVoiceMapper;
import com.sbtr.business.calibration.service.ICalibrationVoiceService;
import com.sbtr.common.PageDto;
import com.sbtr.constant.CalibrationConstant;
import com.sbtr.constant.ColumnConstant;
import com.sbtr.open.calibration.dto.CalibrationCountByClassifyDto;
import com.sbtr.open.calibration.dto.CalibrationDetailsDto;
import com.sbtr.open.calibration.dto.CalibrationSearchByDetailsDto;
import com.sbtr.open.calibration.dto.CalibrationVoiceDto;
import com.sbtr.util.BeanCopyUtils;
import com.sbtr.util.PageDtoUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;


/**
 * <p>
 * 标定集 服务实现类
 * </p>
 *
 * @author zengjw5
 */
@Transactional
@Service
public class CalibrationVoiceServiceImpl extends ServiceImpl<CalibrationVoiceMapper, CalibrationVoice>
        implements ICalibrationVoiceService {

    private static final Logger logger = LoggerFactory.getLogger(CalibrationVoiceServiceImpl.class);

    @Value("${oss.config.httpPath}")
    private String httpPath;

    @Autowired
    private CalibrationServiceImpl calibrationService;

    @Autowired
    private CalibrationDetailsServiceImpl calibrationDetailsService;

    @Autowired
    private CalibrationRecordDailyServiceImpl calibrationRecordDailyService;

    @Override
    public boolean batchSave(List<CalibrationVoiceDto> dtos) {
        List<CalibrationVoice> calibrationVoices = BeanCopyUtils.copyProperties(dtos, CalibrationVoice.class);
        return saveBatch(calibrationVoices);
    }

    @Override
    public List<CalibrationCountByClassifyDto> countVoiceHasCalibrated(Long calibrationDetailsId) {
        CalibrationDetailsDto calibrationDetailsDto = calibrationDetailsService.findById(calibrationDetailsId);
        String finisher = calibrationDetailsDto.getFinisher();
        Long calibration_id = calibrationDetailsDto.getCalibrationId();

        List<CalibrationCountByClassifyDto> dtoList = baseMapper.countVoiceHasCalibrated(finisher, calibration_id);
        return dtoList;
    }

    @Override
    public PageDto<CalibrationVoiceDto> getVoiceCalibrate(CalibrationSearchByDetailsDto dto) {
        IPage<CalibrationVoice> page = new Page<>();
        page.setSize(dto.getPageSize());
        page.setCurrent(dto.getPage());
        QueryWrapper<CalibrationVoice> wrapper = new QueryWrapper<>();
        if (null != dto.getId()) {
            wrapper.eq("calibration_id", dto.getId());
        }
        if (StringUtils.isNotEmpty(dto.getFinisher())) {
            wrapper.eq("finisher", dto.getFinisher());
        }
        if (StringUtils.isNotEmpty(dto.getCompleted())) {
            wrapper.eq("completed", dto.getCompleted());
        }
        if (null != dto.getClassifyId()) {
            wrapper.eq("classify_id", dto.getClassifyId());
        }

//		wrapper.orderByDesc("id");
        page = page(page, wrapper);
        PageDto<CalibrationVoiceDto> pageDto = PageDtoUtils.getPageDtoByIPage(page, CalibrationVoiceDto.class);
        List<CalibrationVoiceDto> CalibrationVoiceDtoList = pageDto.getList();
        for (CalibrationVoiceDto calibrationVoiceDto : CalibrationVoiceDtoList) {
            calibrationVoiceDto.setRelativePath(httpPath + calibrationVoiceDto.getRelativePath());
        }
        pageDto.setList(CalibrationVoiceDtoList);
        return pageDto;
    }

    @Override
    public CalibrationVoiceDto findById(Long id) {
        return BeanCopyUtils.copyProperties(getById(id), CalibrationVoiceDto.class);
    }

    @Override
    public List<CalibrationVoiceDto> saveVoiceCalibrate(Long calibrationDetailsId,
                                                        List<CalibrationVoiceDto> dtos) {
        List<CalibrationVoice> calibrationVoices = BeanCopyUtils.copyProperties(dtos, CalibrationVoice.class);

        for (CalibrationVoice detail : calibrationVoices) {
//            detail.setCalibrationId(calibrationId);
            if (null != detail.getClassifyId()) {
                detail.setCompleted("1");
            } else {
                detail.setCompleted("0");
            }
        }
        boolean tag = saveOrUpdateBatch(calibrationVoices);

        if (tag) {
            // 更新发布任务的数据统计
            CalibrationDetailsDto calibrationDetailsDto = calibrationDetailsService.findById(calibrationDetailsId);
            updateCalibrationVoiceCount(calibrationDetailsDto.getCalibrationId());
            //更新个人接受任务的数据统计
//            CalibrationDto calibrationDto=calibrationService.findById(calibrationId);
            updateCalibrationDetailsVoiceCount(calibrationDetailsDto);
            //更新每日标注统计
            updateCalibrationVoiceRecordDaily(calibrationDetailsDto);
        }

        return BeanCopyUtils.copyProperties(calibrationVoices, CalibrationVoiceDto.class);
    }

    @Override
    public List<CalibrationVoiceDto> saveVoiceSkip(Long calibrationDetailsId,
                                                   List<CalibrationVoiceDto> dtos) {
        List<CalibrationVoice> calibrationVoices = BeanCopyUtils.copyProperties(dtos, CalibrationVoice.class);

        for (CalibrationVoice detail : calibrationVoices) {
//            detail.setCalibrationId(calibrationId);
            detail.setCompleted("2");
        }
        boolean tag = saveOrUpdateBatch(calibrationVoices);

        if (tag) {
            // 更新发布任务的数据统计
            CalibrationDetailsDto calibrationDetailsDto = calibrationDetailsService.findById(calibrationDetailsId);
            updateCalibrationVoiceCount(calibrationDetailsDto.getCalibrationId());
            //更新个人接受任务的数据统计
//            CalibrationDto calibrationDto=calibrationService.findById(calibrationId);
            updateCalibrationDetailsVoiceCount(calibrationDetailsDto);
        }

        return BeanCopyUtils.copyProperties(calibrationVoices, CalibrationVoiceDto.class);
    }

    // 更新图片类型的发布任务的数据统计
    public boolean updateCalibrationVoiceCount(Long calibrationId) {
        Calibration calibration = calibrationService.getById(calibrationId);
        if (null != calibration) {
            QueryWrapper<CalibrationVoice> wrapper = new QueryWrapper<>();
            wrapper.eq("calibration_id", calibrationId);
            Integer totalCount = count(wrapper);
            wrapper.eq("completed", "1");
            Integer completeCount = count(wrapper);

            calibration.setTotalCount(totalCount);
            calibration.setCompleted(completeCount);
            if (completeCount.equals(totalCount)) {
                calibration.setStatus(CalibrationConstant.TASK_STATUS_COMPLETED);
            }

            return calibrationService.updateById(calibration);
        }
        return false;
    }

    // 更新图片类型的个人接受任务的数据统计
    public boolean updateCalibrationDetailsVoiceCount(CalibrationDetailsDto calibrationDetailsDto) {

        QueryWrapper<CalibrationVoice> wrapper = new QueryWrapper<>();
        Long calibrationIds = calibrationDetailsDto.getCalibrationId();
        String finisher = calibrationDetailsDto.getFinisher();
        wrapper.eq("calibration_id", calibrationIds);
        wrapper.eq("finisher", finisher);
        Integer totalCount = count(wrapper);
        wrapper.eq("completed", "1");
        Integer completeCount = count(wrapper);

        CalibrationDetails calibrationDetails = BeanCopyUtils.copyProperties(calibrationDetailsDto, CalibrationDetails.class);
        calibrationDetails.setTotalCount(totalCount);
        calibrationDetails.setCompleted(completeCount);
        if (completeCount.equals(totalCount)) {
            calibrationDetails.setStatus(CalibrationConstant.TASK_STATUS_COMPLETED);
        }

        return calibrationDetailsService.updateById(calibrationDetails);
    }

    //更新每日标注统计
    public boolean updateCalibrationVoiceRecordDaily(CalibrationDetailsDto calibrationDetails) {
        QueryWrapper<CalibrationVoice> wrapper = new QueryWrapper<>();
        long calibrationId = calibrationDetails.getCalibrationId();
        String finisher = calibrationDetails.getFinisher();
        wrapper.eq("calibration_id", calibrationId);
        wrapper.eq("finisher", finisher);
//		Integer totalCount = count(wrapper);
        wrapper.eq("completed", "1");
        Calendar calendar = new GregorianCalendar();
        //        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(new Date());//当天时间赋给日历对象
        calendar.set(Calendar.HOUR_OF_DAY, 0);//设置对象日历格式
        calendar.set(Calendar.MINUTE, 0);//设置为当天零点
        calendar.set(Calendar.SECOND, 0);
        Date updateTimeFrom = calendar.getTime();//再返回时间对象
        calendar.add(Calendar.DAY_OF_MONTH, 1);//把日期往后增加一天,整数  往后推,负数往前移动
        Date updateTimeTo = calendar.getTime();//返回另一个时间对象
        wrapper.between(ColumnConstant.UPDATE_TIME, updateTimeFrom, updateTimeTo);
        Integer completeCount = count(wrapper);
        CalibrationRecordDaily calibrationRecordDaily = calibrationRecordDailyService.findByCalibrationIdFinisher(calibrationId, finisher);
        if (null == calibrationRecordDaily) {
            calibrationRecordDaily = new CalibrationRecordDaily();
            calibrationRecordDaily.setCalibrationId(calibrationId);
            calibrationRecordDaily.setFinisher(finisher);
            calibrationRecordDaily.setCalibrationDetailId(calibrationDetails.getId());
            calibrationRecordDaily.setUpdateTime(new Date());
            calibrationRecordDaily.setCompletedCount(completeCount);
        } else {
            calibrationRecordDaily.setUpdateTime(new Date());
            calibrationRecordDaily.setCompletedCount(completeCount);
        }
        return calibrationRecordDailyService.saveOrUpdate(calibrationRecordDaily);
    }

    @Override
    public List<CalibrationVoiceDto> findCompletedByCalibrationId(Long calibrationId) {
        QueryWrapper<CalibrationVoice> wrapper = new QueryWrapper<>();
        wrapper.eq("calibration_id", calibrationId);
        wrapper.eq("completed", "1");
        List<CalibrationVoice> calibrationVoiceList = list(wrapper);
        return BeanCopyUtils.copyProperties(calibrationVoiceList, CalibrationVoiceDto.class);
    }

    @Override
    public List<CalibrationVoiceDto> findCompletedByFinisher(Long calibrationId, String finisher) {
        QueryWrapper<CalibrationVoice> wrapper = new QueryWrapper<>();
        wrapper.eq("calibration_id", calibrationId);
        wrapper.eq("finisher", finisher);
        wrapper.eq("completed", "1");
        List<CalibrationVoice> calibrationVoiceList = list(wrapper);
        return BeanCopyUtils.copyProperties(calibrationVoiceList, CalibrationVoiceDto.class);
    }

}